'use client'

import {useCallback, useState} from 'react'
import {ProLayout} from '@ant-design/pro-components'
import {Button, Dropdown, message, Tabs, Tooltip} from 'antd'
import {usePathname, useRouter} from 'next/navigation'
import {RouteItem, routes} from '../routes'
import HomePage from './page'
import PurchasePage from '../purchase/page'
import ProductsPage from '../products/page'
import InventoryPage from '../inventory/page'
import SalesPage from '../sales/page'
import UsersPage from '../system/users/page'
import RolesPage from '../system/roles/page'
import MenusPage from '../system/menus/page'
import SettingsPage from '../system/settings/page'
import {FullscreenExitOutlined, FullscreenOutlined, LogoutOutlined,} from '@ant-design/icons'

type TabItem = {
  key: string
  label: string
  children: React.ReactNode
  closable?: boolean
}

const componentMap: Record<string, React.ReactNode> = {
  '/home': <HomePage />,
  '/purchase': <PurchasePage />,
  '/products': <ProductsPage />,
  '/inventory': <InventoryPage />,
  '/sales': <SalesPage />,
  '/system/users': <UsersPage />,
  '/system/roles': <RolesPage />,
  '/system/menus': <MenusPage />,
  '/system/settings': <SettingsPage />,
}

export default function MainLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const router = useRouter()
  const pathname = usePathname()
  const [activeKey, setActiveKey] = useState('/home')
  const [isFullscreen, setIsFullscreen] = useState(false)
  const [tabs, setTabs] = useState<TabItem[]>([
    {
      key: '/home',
      label: '首页',
      children: componentMap['/home'],
      closable: false,
    },
  ])

  const handleLogout = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    message.success('已退出登录')
    router.replace('/login')
  }

  const toggleFullscreen = useCallback(() => {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen()
      setIsFullscreen(true)
    } else {
      document.exitFullscreen()
      setIsFullscreen(false)
    }
  }, [])

  const handleTabChange = (key: string) => {
    setActiveKey(key)
  }

  const handleTabEdit = (targetKey: string | React.MouseEvent | React.KeyboardEvent, action: 'add' | 'remove') => {
    if (action === 'remove' && typeof targetKey === 'string') {
      const newTabs = tabs.filter((tab) => tab.key !== targetKey)
      setTabs(newTabs)
      // 如果关闭的是当前标签，则切换到最后一个标签
      if (targetKey === activeKey) {
        const lastTab = newTabs[newTabs.length - 1]
        setActiveKey(lastTab.key)
      }
    }
  }

  const handleMenuClick = (path: string) => {
    // 如果标签已存在，直接切换
    if (tabs.find((tab) => tab.key === path)) {
      setActiveKey(path)
      return
    }

    // 找到路由对应的标题
    const route = routes.find((route: RouteItem) => route.path === path)
    if (!route) return

    // 添加新标签
    const newTab: TabItem = {
      key: path,
      label: route.name,
      children: componentMap[path],
      closable: true,
    }
    setTabs([...tabs, newTab])
    setActiveKey(path)
  }

  const handleCloseAll = () => {
    const homeTab = tabs.find((tab) => !tab.closable)
    if (homeTab) {
      setTabs([homeTab])
      setActiveKey(homeTab.key)
    }
  }

  const handleCloseOthers = () => {
    const currentTab = tabs.find((tab) => tab.key === activeKey)
    const homeTab = tabs.find((tab) => !tab.closable)
    if (currentTab && homeTab) {
      setTabs(currentTab.key === homeTab.key ? [homeTab] : [homeTab, currentTab])
    }
  }

  const tabBarExtraContent = {
    right: (
      <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
        <Dropdown
          menu={{
            items: [
              {
                key: 'closeAll',
                label: '关闭所有',
                onClick: handleCloseAll,
              },
              {
                key: 'closeOthers',
                label: '关闭其他',
                onClick: handleCloseOthers,
              },
              {
                type: 'divider',
              },
              {
                key: 'logout',
                label: '退出登录',
                icon: <LogoutOutlined />,
                onClick: handleLogout,
              },
            ],
          }}
        >
          <a onClick={(e) => e.preventDefault()} style={{ padding: '0 8px' }}>
            操作 ⌄
          </a>
        </Dropdown>
        <Tooltip title={isFullscreen ? '退出全屏' : '全屏'}>
          <Button
            type="text"
            icon={isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
            onClick={toggleFullscreen}
          />
        </Tooltip>
      </div>
    ),
  }

  return (
    <ProLayout
      route={{ routes }}
      location={{
        pathname: activeKey,
      }}
      title="OmniStock"
      logo={null}
      menuItemRender={(item, dom) => (
        <a
          onClick={() => {
            handleMenuClick(item.path || '/home')
          }}
        >
          {dom}
        </a>
      )}
      contentStyle={{
        margin: 0,
        padding: 0,
      }}
      style={{
        height: '100vh',
      }}
    >
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <Tabs
          type="editable-card"
          onChange={handleTabChange}
          activeKey={activeKey}
          onEdit={handleTabEdit}
          items={tabs}
          tabBarExtraContent={tabBarExtraContent}
          style={{ flex: 1, margin: 0 }}
          tabBarStyle={{ margin: 0, padding: '8px 8px 0' }}
          hideAdd={true}
        />
      </div>
    </ProLayout>
  )
} 